package rexsee.core.alarm;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.content.Context;
import android.os.PowerManager;

public class RexseeWakeLock implements JavascriptInterface {

	public static final String INTERFACE_NAME = "WakeLock";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeWakeLock(childBrowser);
	}

	private final Context mContext;
	private final Browser mBrowser;
	private PowerManager.WakeLock mWakeLock = null;

	public RexseeWakeLock(Browser browser) {
		mBrowser = browser;
		mContext = browser.getContext();
	}
	public RexseeWakeLock(Context context) {
		mBrowser = null;
		mContext = context;
	}

	//JavaScript interface
	public void acquire(boolean onAfterRelease) {
		release();
		PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
		int mode = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
		if (onAfterRelease) {
			mode = mode | PowerManager.ON_AFTER_RELEASE;
		}
		mWakeLock = pm.newWakeLock(mode, "");
		mWakeLock.acquire();
	}
	public void release() {
		if (mWakeLock != null) {
			mWakeLock.release();
			mWakeLock = null;
		}
	}

}
